package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketLogMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.model.admin.vo.AdminAuthInfoVo;
import com.cskaoyan.model.admin.vo.AdminInfoBean;
import com.cskaoyan.model.admin.vo.LoginUserData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/3 15:36
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Autowired
    MarketLogMapper marketLogMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Override
    public LoginUserData adminLogin(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        Subject subject = SecurityUtils.getSubject();
        MarketLog marketLog = new MarketLog();
        Date date = new Date();
        try {
            subject.login(new UsernamePasswordToken(username, password));
        } catch (AuthenticationException e) {
            marketLog.setAddTime(date);
            marketLog.setAdmin("匿名用户");
            marketLog.setAction("登录");
            marketLog.setDeleted(false);
            marketLog.setStatus(false);
            marketLog.setIp(subject.getSession().getHost());
            marketLog.setType(0);
            marketLog.setResult("用户名或密码错误");
            return null;
        }
        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(example);
        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar(marketAdmins.get(0).getAvatar());
        adminInfo.setNickName(marketAdmins.get(0).getUsername());
        loginUserData.setAdminInfo(adminInfo);


        subject.getSession().setAttribute("userId", marketAdmins.get(0).getId());
        subject.getSession().getAttribute("userId");
        loginUserData.setToken((String) subject.getSession().getId());


        marketLog.setAddTime(date);
        marketLog.setAdmin(marketAdmins.get(0).getUsername());
        marketLog.setAction("登录");
        marketLog.setDeleted(false);
        marketLog.setStatus(true);
        marketLog.setIp(subject.getSession().getHost());
        marketLog.setType(0);
        marketLog.setResult("成功");
        marketLogMapper.insertSelective(marketLog);

        return loginUserData;
    }

    @Override
    public void adminLogout(HttpSession httpSession) {
        Integer userId = (Integer) httpSession.getAttribute("userId");
        Date date = new Date();
        MarketLog marketLog = new MarketLog();
        marketLog.setStatus(true);
        MarketAdminExample example = new MarketAdminExample();
        example.createCriteria().andIdEqualTo(userId);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(example);
        marketLog.setAdmin(marketAdmins.get(0).getUsername());
        Subject subject = SecurityUtils.getSubject();
        marketLog.setIp(subject.getSession().getHost());
        marketLog.setStatus(true);
        marketLog.setDeleted(false);
        marketLog.setAction("退出");
        marketLog.setAddTime(date);
        marketLog.setType(0);
        marketLog.setResult("成功");
        marketLog.setUpdateTime(date);
        marketLogMapper.insertSelective(marketLog);
        httpSession.invalidate();
    }

    @Override
    public AdminAuthInfoVo authInfo(String token) {
        MarketAdminExample example = new MarketAdminExample();
        MarketPermissionExample permissionExample = new MarketPermissionExample();
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        example.createCriteria().andUsernameEqualTo(username);
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(example);
        String roleIds = marketAdmins.get(0).getRoleIds();
        String[] split = roleIds.replace("[", "").replace("]", "").split(",");
        List<String> perms = new ArrayList<>();
        List<String> roles = new ArrayList<>();
        for (String s : split) {
            MarketRoleExample example1 = new MarketRoleExample();
            example1.createCriteria().andIdEqualTo(Integer.parseInt(s));
            if ("1".equals(s)) {
                perms.add("*");
                break;
            }
            List<MarketRole> marketRoles = marketRoleMapper.selectByExample(example1);
            for (MarketRole marketRole : marketRoles) {
                roles.add(marketRole.getName());
            }
            permissionExample.createCriteria().andRoleIdEqualTo(Integer.parseInt(s));
            List<MarketPermission> marketPermissions = marketPermissionMapper.selectByExample(permissionExample);
            for (MarketPermission marketPermission : marketPermissions) {
                perms.add(marketPermission.getPermission());
            }
        }

        AdminAuthInfoVo adminAuthInfoVo = new AdminAuthInfoVo();
        adminAuthInfoVo.setName(username);
        adminAuthInfoVo.setPerms(perms);
        adminAuthInfoVo.setAvatar(marketAdmins.get(0).getAvatar());
        adminAuthInfoVo.setRoles(roles);
        return adminAuthInfoVo;
    }
}
